package baidu.com.matedemo.network;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.common.logging.Log;
import com.baidu.duer.libcore.adapter.CommonAdapter;
import com.baidu.duer.libcore.adapter.ViewHolder;
import com.baidu.duer.libcore.module.permission.PermissionHelper;
import com.baidu.duer.libcore.util.ToastUtil;
import com.baidu.duer.smartmate.duerlink.bean.DuerBleDevice;
import com.baidu.duer.smartmate.duerlink.bean.DuerlinkError;
import com.baidu.duer.smartmate.duerlink.config.DuerlinkConfigManager;
import com.baidu.duer.smartmate.duerlink.config.DuerlinkConfigState;
import com.baidu.duer.smartmate.duerlink.config.IDuerlinkConfigListener;
import com.baidu.duer.smartmate.duerlink.discovery.DuerlinkBleDiscoveryError;
import com.baidu.duer.smartmate.duerlink.discovery.DuerlinkDiscoveryManager;
import com.baidu.duer.smartmate.duerlink.discovery.IDuerlinkBleDiscoveryListener;
import com.baidu.duer.smartmate.out.DuerDevice;
import com.baidu.duer.smartmate.out.oauth.IResponseCallback;

import java.util.ArrayList;
import java.util.List;

import baidu.com.matedemo.DemoApp;
import baidu.com.matedemo.R;
import baidu.com.matedemo.base.BaseActivity;
import baidu.com.matedemo.base.Utils;
import baidu.com.matedemo.pair.DevicePairWrapper;
import baidu.com.matedemo.pair.OauthType;
import baidu.com.matedemo.util.DemoUtils;

/**
 * 蓝牙配网
 */
public class BLEConfigurationActivity extends BaseActivity {
    private DuerlinkDiscoveryManager duerlinkDiscoveryManager = null;
    private DuerlinkConfigManager duerlinkConfigManager = null;
    private EditText ssidEditText = null;
    private EditText passwordEditText = null;
    private ArrayList<String> logList = null;
    private CommonAdapter<String> logAdapter = null;
    private ListView logListView = null;
    private ArrayList<DuerBleDevice> bleDeviceList = null;
    private CommonAdapter<DuerBleDevice> bleDeviceAdapter = null;
    private ListView bleDeviceListView = null;
    private DevicePairWrapper pairWrapper = null;
    private static final int REQUEST_CODE_LOCATION_SETTINGS = 1;
    private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 2;

    @Override
    public View onCreateContentViewCompat(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.wifi_configuration, viewGroup, false);
    }

    @Override
    public void onContentViewCreated(View view) {
        super.onContentViewCreated(view);
        TextView oauthView = (TextView) findViewById(R.id.oauth_view);
        oauthView.setText("当前选择为");
        OauthType oauthType = DemoApp.getInstance().getOauthType();
        if (OauthType.AUTHORIZATION_CODE.equals(oauthType)) {
            oauthView.append("合作对接产品，采用oauth标准授权方式，请确定已向度秘团队申请开通授权");
        } else if (OauthType.PRIVILEGE_OAUTH.equals(oauthType)) {
            oauthView.append("百度自有产品，采用privilege授权方式，请确定已向度秘团队申请开通授权");
        } else if (OauthType.DEVICE_CODE.equals(oauthType)) {
            oauthView.append("普通开发者产品，采用device code授权方式");
        }
        ssidEditText = (EditText) findViewById(R.id.ssid_edit_text);
        passwordEditText = (EditText) findViewById(R.id.password_edit_text);
        bleDeviceListView = (ListView) findViewById(R.id.device_list_view);
        logListView = (ListView) findViewById(R.id.log_list_view);
        duerlinkDiscoveryManager = new DuerlinkDiscoveryManager(getApplicationContext());
        duerlinkConfigManager = new DuerlinkConfigManager(getApplicationContext());
        bleDeviceList = new ArrayList<>();

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        ssidEditText.setText(Utils.removeQuote(wifiInfo.getSSID()));

        if (BluetoothAdapter.getDefaultAdapter() == null || !BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            ToastUtil.toastWarnning(BLEConfigurationActivity.this, "请先打开蓝牙，才能使用");
            finish();
        }

        // 确保有Location权限以获取Wi-Fi/BLE扫描结果
        if (!PermissionHelper.hasPermission(this, "android.permission.ACCESS_COARSE_LOCATION")) {
            PermissionHelper.requestPermission(this,
                    REQUEST_CODE_ACCESS_COARSE_LOCATION,
                    new String[]{"android.permission.ACCESS_COARSE_LOCATION"},
                    R.string.request_location_permission,
                    new PermissionHelper.Listener() {
                        @Override
                        public void onSucceed() {
                            Log.i(BLEConfigurationActivity.class.getSimpleName(), "got location permission");
                            onGotLocationPermission();
                        }

                        @Override
                        public void onFailed() {
                        }
                    });
        } else {
            Log.i(BLEConfigurationActivity.class.getSimpleName(), "already has location permission");
            onGotLocationPermission();
        }

        bleDeviceAdapter = new CommonAdapter<DuerBleDevice>(this, R.layout.item_function, bleDeviceList) {
            @Override
            protected void convert(ViewHolder viewHolder, DuerBleDevice duerBleDevice, int i) {
                viewHolder.setText(R.id.text_view, duerBleDevice.getBleDeviceName());
            }
        };
        bleDeviceListView.setAdapter(bleDeviceAdapter);
        bleDeviceAdapter.notifyDataSetChanged();
        bleDeviceListView.setOnItemClickListener(getBleListener());

        logList = new ArrayList<>();
        logAdapter = new CommonAdapter<String>(this, R.layout.item_function, logList) {
            @Override
            protected void convert(ViewHolder viewHolder, String s, int i) {
                viewHolder.setText(R.id.text_view, s);
            }
        };
        logListView.setAdapter(logAdapter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 重要！退出页面时，即时注销不再需要的回调！
        if (duerlinkDiscoveryManager != null) {
            duerlinkDiscoveryManager.stopBleDiscovery();
        }
        if (duerlinkConfigManager != null) {
            duerlinkConfigManager.stopConfig();
        }
        if (pairWrapper != null) {
            pairWrapper.stopPair();
        }
    }

    private IDuerlinkBleDiscoveryListener getBleDiscoveryListener() {
        return new IDuerlinkBleDiscoveryListener() {
            @Override
            public void onDiscovery(DuerBleDevice device) {
                Log.i(BLEConfigurationActivity.class.getSimpleName(), "onDiscovery:" + device.getBleDeviceName());
                bleDeviceList.add(device);
                bleDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDiscoveryComplete(List<DuerBleDevice> devices) {
            }

            @Override
            public void onDiscoveryFail(DuerlinkBleDiscoveryError error) {
            }
        };
    }

    private AdapterView.OnItemClickListener getBleListener() {
        return new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String ssid = ssidEditText.getText().toString().trim();
                if (TextUtils.isEmpty(ssid)) {
                    Toast.makeText(BLEConfigurationActivity.this, "请填写wifi名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                String pwd = passwordEditText.getText().toString().trim();
                if (TextUtils.isEmpty(pwd)) {
                    Toast.makeText(BLEConfigurationActivity.this, "请填写wifi密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                showProgressBar();

                DuerBleDevice duerBleDevice = bleDeviceList.get(i);
                if (duerlinkDiscoveryManager != null) {
                    duerlinkDiscoveryManager.stopBleDiscovery();
                }
                duerlinkConfigManager.startConfig(duerBleDevice,
                        ssidEditText.getText().toString(),
                        passwordEditText.getText().toString(),
                        new IDuerlinkConfigListener() {
                            @Override
                            public void onSuccess(final DuerDevice device) {
                                logList.add("wifi  config success");
                                logAdapter.notifyDataSetChanged();
                                ToastUtil.toastSuccess(BLEConfigurationActivity.this, "配网成功");
                                if (DemoApp.getInstance().getOauthType() == null) {
                                    // 仅配网，不授权
                                    DemoApp.getInstance().addDuerDevice(device);
                                    DemoApp.getInstance().setCurrentDevice(device);
                                    finish();
                                    return;
                                }

                                //配对
                                IResponseCallback responseCallback = new IResponseCallback() {
                                    @Override
                                    public void onSuccess() {
                                        dismissProgressBar();
                                        // 配网完成，跳转到授权页面
                                        DemoApp.getInstance().addDuerDevice(device);
                                        DemoApp.getInstance().setCurrentDevice(device);
                                        ToastUtil.toastSuccess(BLEConfigurationActivity.this, "授权成功");
                                        finish();
                                    }

                                    @Override
                                    public void onError(long status, String msg) {
                                        dismissProgressBar();
                                        ToastUtil.toastSuccess(BLEConfigurationActivity.this, "授权失败");
                                    }
                                };

                                pairWrapper = new DevicePairWrapper();
                                pairWrapper.startPair(BLEConfigurationActivity.this,
                                        DemoApp.getInstance().getOauthType(),
                                        device,
                                        responseCallback);
                            }

                            @Override
                            public void onFail(DuerlinkError error) {
                                dismissProgressBar();
                                logList.add("config fail " + error);
                                logAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onStateChanged(DuerlinkConfigState state) {
                                logList.add(state.toString());
                                logAdapter.notifyDataSetChanged();
                            }
                        });
            }
        };
    }

    private void onGotLocationPermission() {
        if (DemoUtils.isLocationEnabled(BLEConfigurationActivity.this)) {
            onLocationSettingEnabled();
        } else {
            enableLocationSetting();
        }
    }

    private void enableLocationSetting() {
        Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        this.startActivityForResult(locationIntent, REQUEST_CODE_LOCATION_SETTINGS);
    }

    private void onLocationSettingEnabled() {
        if (duerlinkDiscoveryManager != null) {
            duerlinkDiscoveryManager.startBleDiscovery(getBleDiscoveryListener());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_LOCATION_SETTINGS) {
            if (DemoUtils.isLocationEnabled(this)) {
                onLocationSettingEnabled();
            }
        }
    }
}
